<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '20px' }" class="mb-5 border-1">
      <!-- 搜索区域 -->
      <el-text class="mx-1 mr-3">公告内容</el-text>
      <el-input v-model="searchContent" placeholder="请输入（模糊查询）" class="w-50 mr-5" />

      <el-text class="mx-1 mr-3">状态</el-text>
      <el-select v-model="isEnabled" placeholder="请选择状态" class="w-32 mr-5">
        <el-option label="全部" value="" />
        <el-option label="启用" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>

      <el-button type="primary" class="ml-3" @click="getTableData">查询</el-button>
      <el-button class="ml-3" @click="reset">重置</el-button>
    </el-card>

    <el-card shadow="never" class="border-1">
      <!-- 操作按钮 -->
      <div>
        <el-button type="primary" @click="showAnnouncementEditor">
          <el-icon class="mr-1">
            <EditPen />
          </el-icon>
          新增公告
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" stripe style="width: 100%" class="mt-4" v-loading="tableLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="公告内容" min-width="400">
          <template #default="scope">
            <el-tooltip :content="scope.row.content" placement="top">
              <span>{{ scope.row.content.length > 50 ? scope.row.content.substring(0, 50) + '...' : scope.row.content }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.isEnabled" 
              :active-value="1" 
              :inactive-value="0" 
              @change="updateAnnouncementStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="showAnnouncementEditor(scope.row)">
              <el-icon class="mr-1">
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteAnnouncement(scope.row)">
              <el-icon class="mr-1">
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-5 flex item-center justify-center">
        <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 50]" 
          background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" 
          @size-change="handleSizeChange" @current-change="getTableData" />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditorShow" :title="editingAnnouncement.id ? '编辑公告' : '新增公告'" width="600px">
      <el-form :model="editingAnnouncement" ref="announcementFormRef" label-position="top" :rules="rules">
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="editingAnnouncement.content" type="textarea" placeholder="请输入公告内容" 
            :rows="4" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="editingAnnouncement.isEnabled" 
            :active-value="1" 
            :inactive-value="0" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditor">取消</el-button>
          <el-button type="primary" @click="submitAnnouncement">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAnnouncementList, saveAnnouncement, deleteAnnouncement as deleteAnnouncementApi } from '@/api/frontend/announcement'

// 搜索条件
const searchContent = ref('')
const isEnabled = ref('')

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const current = ref(1)
const size = ref(10)
const total = ref(0)

// 编辑器状态
const isEditorShow = ref(false)
const announcementFormRef = ref()
const editingAnnouncement = reactive({
  id: '',
  content: '',
  isEnabled: 1 // 改为数字类型
})

// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 1, max: 200, message: '公告内容长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取表格数据
const getTableData = async () => {
  tableLoading.value = true
  try {
    const params = {
      current: current.value,
      size: size.value,
      content: searchContent.value,
      isEnabled: isEnabled.value
    }
    const res = await getAnnouncementList(params)
    if (res.success) {
      tableData.value = res.data.records || res.data
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 重置搜索条件
const reset = () => {
  searchContent.value = ''
  isEnabled.value = ''
  current.value = 1
  getTableData()
}

// 分页大小变化
const handleSizeChange = (newSize) => {
  size.value = newSize
  current.value = 1
  getTableData()
}

// 显示编辑器
const showAnnouncementEditor = (announcement = null) => {
  // 重置表单
  if (announcementFormRef.value) {
    announcementFormRef.value.resetFields()
  }
  
  // 设置编辑数据
  if (announcement) {
    Object.assign(editingAnnouncement, {
      ...announcement,
      isEnabled: Number(announcement.isEnabled) // 确保是数字类型
    })
  } else {
    Object.assign(editingAnnouncement, {
      id: '',
      content: '',
      isEnabled: 1
    })
  }
  
  isEditorShow.value = true
}

// 关闭编辑器
const closeEditor = () => {
  isEditorShow.value = false
}

// 提交公告
const submitAnnouncement = async () => {
  if (!announcementFormRef.value) return
  
  try {
    await announcementFormRef.value.validate()
    
    const requestData = {
      ...editingAnnouncement
    }
    
    const res = await saveAnnouncement(requestData)
    if (res.success) {
      ElMessage.success(editingAnnouncement.id ? '更新成功' : '创建成功')
      isEditorShow.value = false
      getTableData()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('提交公告失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 更新公告状态
const updateAnnouncementStatus = async (announcement) => {
  try {
    const requestData = {
      id: announcement.id,
      content: announcement.content,
      isEnabled: announcement.isEnabled
    }
    
    const res = await saveAnnouncement(requestData)
    if (!res.success) {
      // 回滚状态
      announcement.isEnabled = announcement.isEnabled === 1 ? 0 : 1
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新公告状态失败:', error)
    // 回滚状态
    announcement.isEnabled = announcement.isEnabled === 1 ? 0 : 1
    ElMessage.error('更新失败')
  }
}

// 删除公告
const deleteAnnouncement = (announcement) => {
  if (announcement.isEnabled === 1) {
    ElMessage.warning('启用的公告不能删除，请先禁用后再删除')
    return
  }
  ElMessageBox.confirm(
    `确定要删除该公告吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteAnnouncementApi(announcement.id)
      if (res.success) {
        ElMessage.success('删除成功')
        // 从当前列表中移除该公告
        const index = tableData.value.findIndex(item => item.id === announcement.id)
        if (index > -1) {
          tableData.value.splice(index, 1)
        }
        // 同时刷新列表确保数据一致性
        getTableData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除公告失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 初始化加载数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>